package app.service.impl;

import app.dao.DaoUser;
import app.domain.User;
import app.service.ServiceUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ServiceUserImpl implements ServiceUser {
    @Autowired
    private DaoUser repository;
    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    @CachePut(key = "#p0.username", value = "my-redis-cache2")
    public User insert(User user) {
        //加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        repository.save(user);
        return query(user.getUsername());
    }

    @CacheEvict(key = "#p0.username", value = "my-redis-cache2")
    @Override
    public void delete(User user) {
        repository.delete(user);
    }

    @Override
    @CachePut(key = "#p0.username", value = "my-redis-cache2")
    public User update(User user) {
        //加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        repository.update(user.getId(), user.getUsername(), user.getPassword());
        return query(user.getUsername());
    }

    @Override
    //事务处理 查询操作为只读 如果其他bean调用这个方法,在其他bean中声明事务,那就用事务.如果其他bean没有声明事务,那就不用事务
    @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
    @Cacheable(value = "my-redis-cache2")
    public List<User> querys() {
        return repository.findAll();
    }

    @Override
    //加入缓存以解决每次查询都会查数据库,降低效率的问题
    @Cacheable(key = "#p0",value = "my-redis-cache2")
    @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
    public User query(String username) {
        return repository.getByUsername(username);
    }
}